package cn.jh.clearing.service;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.jh.clearing.business.PaymentOrderBusiness;
import cn.jh.clearing.pojo.PaymentOrder;
import cn.jh.clearing.util.Util;


@Configuration
@Controller
@EnableScheduling
public class WaitClearingTask {

	private final Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private PaymentOrderBusiness paymentOrderBusiness;

	@Autowired
	Util util;

	@Autowired
	private PaymentService paymentService;

	@Value("${schedule-task.on-off}")
	private String scheduleTaskOnOff;

	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/transactionclear/test1")
	public @ResponseBody Object test() {
		scheduler();
		return "OK";
	}

	/**
	 * 周一早上10
	 * 
	 */
	@Scheduled(cron = "0 10 0 ? * MON-FRI")
	public void scheduler() {
        if (!"true".equals(scheduleTaskOnOff)) {
            logger.info("没有开启清算计划任务");
            return;
        }
        List<PaymentOrder> paymentOrders = paymentOrderBusiness.queryWaitClearingOrders();
        int allCount = 0;
        if (paymentOrders != null) {
            allCount = paymentOrders.size();
        }
        if (allCount == 0) {
            logger.info("没有新的交易订单，不执行清算任务！");
            return;
        }

        logger.trace("开始执行。。。。。。。。。。。。。。。。。。。。。。。。。。。WaitClearingTask:订单总数:" + allCount);
        int successCount = 0;
        int failedCount = 0;
        for (PaymentOrder order : paymentOrders) {
            logger.trace("修改订单开始========================================订单号" + order.getOrdercode());
            try {
                paymentService.updatePaymentOrder(order.getOrdercode(), "1", null, null);
            } catch (Exception e) {
                e.printStackTrace();
                logger.error(
                        "修改订单失败=====================================失败订单号:" + order.getOrdercode() + ",失败原因:" + e);
                failedCount += 1;
                continue;
            }
            logger.trace("修改订单结束" + order.getOrdercode());
            successCount += 1;
        }
        logger.trace("==========================成功数:" + successCount);
        logger.trace("==========================失败数:" + failedCount);
	}
}
